import { isEmptyObject } from '@/utils/tool';
import { reqSelectedPool, reqTrackPool, reqSignalList } from '@/apis/pool.api';
import { SELECTED_POOL_STOCK_STATUS, TRACKING_POOL_STOCK_STATUS, POOL_LIST } from '@/config/pool';
import { getWebHQ } from '@/utils';
import tools from '@/lib/tools';
import { localStorageKey, localStorageFeatureHomeTips } from '@/config/pool.js';
const homeTipsTimeStorage = new tools.LocalStorageManager(
  localStorageKey,
  localStorageFeatureHomeTips
);
const fmtStr = 'yyyy-MM-dd';

export default {
  data() {
    return {
      showLoading: false,
      // 全量数据
      dataList: [],
      // 列表展示数据
      stockList: [],
      // 卡片展示数据
      cardList: [],
      // 按日期分类全量数据
      tableMap: {},
      // 按日期分类卡片数据
      cardMap: {},
      showDatePick: false,
      showCalendar: false,
      defaultDate: null,
      minDate: new Date(new Date().getFullYear() - Number('3'), 0, 1),
      maxDate: new Date(),
      validDates: [],
      renewalDate: [],
      weeksMap: {
        0: '周日',
        1: '周一',
        2: '周二',
        3: '周三',
        4: '周四',
        5: '周五',
        6: '周六',
      },
    };
  },
  methods: {
    changeDefaultDate(defaultDate) {
      homeTipsTimeStorage.setItem(`${window.getParam('gpc_id')}.showed`, true);
      this.activeStock = '';
      this.activeDate = '';
      this.defaultDate = defaultDate;
      this.getValidDate();
      this.$nextTick(() => {
        this.highlightDate();
      });
    },
    formatter(day) {
      if (
        this.renewalDate.includes(tools.getMidnightTimestamp(day.date)) &&
        !homeTipsTimeStorage.getItem(`${window.getParam('gpc_id')}.showed`)
      ) {
        day.topInfo = '更新';
        day.className = 'renewal-day';
      }
      return day;
    },
    weekFormatter(date) {
      if (
        this.renewalDate.includes(tools.getMidnightTimestamp(date)) &&
        !homeTipsTimeStorage.getItem(`${window.getParam('gpc_id')}.showed`)
      ) {
        return '更新';
      } else {
        return this.weeksMap[date.getDay()];
      }
    },
    highlightDate() {
      const $renewalDom = $('.atom-calendar-tab__item-week:contains("更新")');
      $renewalDom.length && $renewalDom.css({ color: '#FF2436' });
      const $Doms = $('.atom-calendar-tab__item-week');
      $Doms.each(function () {
        if ($(this).text().indexOf('更新') === -1) {
          $(this).css({ color: '' });
        }
      });
    },

    /**
     * 获取精选池列表
     */
    async getSelectedPool(gpcId) {
      const query = {
        gpcId,
        status: SELECTED_POOL_STOCK_STATUS,
        version: 2,
      };
      try {
        const res = await reqSelectedPool(query);
        if (res.code === 0 && res?.data) {
          return res.data;
        } else {
          return [];
        }
      } catch (err) {
        return [];
      }
    },

    /**
     * 获取跟踪池列表
     */
    async getTackPool(gpcId) {
      const query = {
        gpc_id: gpcId,
        status: TRACKING_POOL_STOCK_STATUS,
      };
      try {
        const res = await reqTrackPool(query);
        if (res.status_code === 0 && res?.data) {
          return res.data;
        } else {
          return [];
        }
      } catch (err) {
        return [];
      }
    },

    /**
     * 处理接口返回数据
     */
    async handleDataList(list) {
      list.forEach((item, idx) => {
        item['codeIndex'] = `${item['stock_code']}-${idx}`;
      });
      const group1 = list.filter(item => !!item['add_date']);
      const group2 = list.filter(item => !item['add_date']);
      // 过滤出来买入时间为空的情况（取消买入和 买入失败）按照入选时间排序
      group1.sort((a, b) => (a['add_date'] < b['add_date'] ? 1 : -1));
      group2.sort((a, b) => (a['add_date'] < b['add_date'] ? 1 : -1));
      const tableData = JSON.parse(JSON.stringify([...group1, ...group2]));
      // 筛选有效状态
      const group3 = tableData.filter(item =>
        ['2', '3', '8', '10', '11'].includes(`${item.status}`)
      );
      const group4 = tableData.filter(item => ['4', '5', '6', '7', '9'].includes(`${item.status}`));
      const dataLists = JSON.parse(JSON.stringify([...group3, ...group4]));
      this.dataList = await getWebHQ(dataLists);
      this.handleTableList();
    },

    handleTableList() {
      for (const item of this.dataList) {
        const date = item['add_date'].slice(0, Number('10'));
        const dateList = this.tableMap[date] || [];
        if (dateList.length) {
          const flag = dateList.find(d => d.codeIndex === item.codeIndex) ? false : true;
          if (flag) {
            this.tableMap[date].push(item);
          }
        } else {
          this.tableMap[date] = [item];
        }
      }
    },

    handleSignalData(res) {
      for (const date of Object.keys(this.tableMap)) {
        this.cardMap[date] = [];
        for (const item of this.tableMap[date]) {
          this.cardMap[date].push(res.data?.[item.id]);
        }
      }
    },

    async getSignalList() {
      const stockIds = this.dataList.map(data => data.id);
      try {
        const res = await reqSignalList({
          gpc_id: POOL_LIST[window.getParam('product')][window.getParam('gpc_id')].msgId,
          stock_ids: stockIds,
        });
        if (res.status_code === 0 && !isEmptyObject(res.data)) {
          this.handleSignalData(res);
        } else {
          throw new Error(`detail的mixins里reqSignalList接口statu_code：${res.status_code}`);
        }
      } catch (error) {
        _t.errorReport({
          ...error,
        });
      }
    },

    getValidDate() {
      try {
        this.validDates = Object.keys(this.tableMap).sort(
          (a, b) => new Date(b).getTime() - new Date(a).getTime()
        );
        let dateStr = '';
        if (this.defaultDate) {
          dateStr = window.Acme.formatDate(this.defaultDate, fmtStr);
        } else {
          dateStr = this.validDates[0];
          this.defaultDate = new Date(this?.activeDate || dateStr);
        }
        const carObj = this.cardMap[dateStr.slice(0, 10)] || [];
        this.cardList = [...carObj];
        this.stockList = [...this.tableMap[dateStr.slice(0, 10)]];
        this.showDatePick = true;
        setTimeout(() => {
          this.highlightDate();
        });
      } catch (err) {
        const errInfo = {
          name: 'js执行异常',
          message: err,
          stack: 'getValidDate',
          category: 'js',
        };
        _t.errorReport(errInfo);
      }
    },

    /**
     * calendar-tab显示有效的日期
     */
    filterDate(days) {
      return days.filter(day => this.validDates.includes(window.Acme.formatDate(day, fmtStr)));
    },

    /**
     * calendar显示有效的日期
     */
    filterCalendar(date) {
      return this.validDates.includes(window.Acme.formatDate(date, fmtStr));
    },

    show() {
      this.showCalendar = true;
    },

    confirm(date) {
      this.showCalendar = false;
      this.defaultDate = date;
      this.getValidDate();
    },
  },
};
